package com.hfjyz.base.util;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.jxls.reader.ReaderBuilder;
import net.sf.jxls.reader.XLSReadStatus;
import net.sf.jxls.reader.XLSReader;
import net.sf.jxls.transformer.XLSTransformer;

import org.apache.poi.hssf.usermodel.HSSFPicture;
import org.apache.poi.hssf.usermodel.HSSFPictureData;
import org.apache.poi.hssf.usermodel.HSSFShape;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import com.hfjyz.base.bean.BaseBean;

public final class ExcelUtil<T extends BaseBean> {
    public XLSReadStatus readFromExcel(InputStream xmlTemplate, InputStream inputXLS, T bean, String beanName)
            throws Exception {
        XLSReader mainReader = ReaderBuilder.buildFromXML(xmlTemplate);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(beanName, bean);
        XLSReadStatus status = mainReader.read(inputXLS, map);

        return status;
    }

    public Workbook writeToExcel(InputStream template, T bean, String beanName)
            throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(beanName, bean);

        XLSTransformer transformer = new XLSTransformer();
        Workbook wb = transformer.transformXLS(template, map);

        return wb;
    }

    public Workbook writeToExcel(InputStream template, List<T> beanList, String beanListName)
            throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(beanListName, beanList);

        XLSTransformer transformer = new XLSTransformer();
        Workbook wb = transformer.transformXLS(template, map);

        return wb;
    }
    
    public static byte[] readerImageFromExcel(InputStream inputStream) throws Exception {
        HSSFWorkbook workbook = (HSSFWorkbook) WorkbookFactory.create(inputStream);

        List<HSSFPictureData> pictures = workbook.getAllPictures();
        HSSFSheet sheet = (HSSFSheet) workbook.getSheetAt(0);

        if (sheet != null && sheet.getDrawingPatriarch() != null && sheet.getDrawingPatriarch().getChildren() != null) {
            for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren()) {
                if (shape instanceof HSSFPicture) {
                    HSSFPicture pic = (HSSFPicture) shape;
                    int pictureIndex = pic.getPictureIndex() - 1;
                    HSSFPictureData picData = pictures.get(pictureIndex);

                    return picData.getData();
                }
            }
        }
        return null;
    }
}
